package com.dippy.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dippy.common.dto.LoginDto;
import com.dippy.common.lang.Result;
import com.dippy.entity.User;
import com.dippy.service.UserService;
import com.dippy.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
public class AccountController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login( @Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        // 1. 通过username查数据库
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));

        // 2. 用户是否为存在。可以使用断言，也可以自己抛异常
        Assert.notNull(user, "用户不存在");

        // 3. 判断密码正不正确
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            // 可以直接返回，也可以抛出异常
            return Result.fail("密码不正确");
        }

        // 4. 账号密码都正确。生成jwt
        String jwt = jwtUtils.generateToken(user.getId());// 这个jwtUtils中需要传入id，可以用别的jwtUtils对应传入相应参数就行

        // 5. 放在请求头hander中
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        // 6. 返回用户信息。用MapUtil来简化书写，最终都是包装成Map
        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map()
        );
    }

    @RequiresAuthentication//shiro的，表示需要登录才能访问
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }

}
